package com.magicode.cms.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.magicode.cms.common.assist.json.JsonOperation;
import com.magicode.cms.dao.IArticleDao;
import com.magicode.cms.dao.impl.ArticleDaoImpl;
import com.magicode.cms.entiy.base.Article;
import com.magicode.cms.entiy.base.News;
import com.magicode.cms.entiy.base.NewsEnterpriseRela;
import com.magicode.cms.entiy.base.NewsPersonRela;
import com.magicode.cms.entiy.base.NewsProgramRela;
import com.magicode.cms.entiy.base.Picture;
import com.magicode.cms.service.IArticleService;
import com.magicode.common.exception.BusinessException;
import com.magicode.common.util.StaticHtmlUtil;

@Service("servicearticle")
public class ArticleServiceImpl  extends BaseServiceImpl<Article, IArticleDao> implements IArticleService{
	
	@Override
	public String getHql(Map<String, String> map) throws Exception {
		String hql ="from " +Article.class.getName()+" "+entity_alias_name+" ";

		hql += " left join "+entity_alias_name+".readOperate as ro ";
		hql += " left join "+entity_alias_name+".channel as ch ";
		hql += " left join "+entity_alias_name+".author as au ";
		if(null!=map && !map.isEmpty()){
			hql += "where 1 = 1  ";  //and "+entity_alias_name+".isContribute = 0
			if(map.containsKey(field_id)){
				hql = hql+" and "+entity_alias_name+".id = '"+map.get(field_id)+"'";
			}
			if(map.containsKey("title")){
				hql = hql+" and "+entity_alias_name+".title like '%"+map.get("title")+"%'";
			}
			if(map.containsKey("status")){
				hql = hql+" and "+entity_alias_name+".status = '"+map.get("status")+"'";
			}
			if(map.containsKey("channelId")){
				hql = hql+" and "+entity_alias_name+".channel.id = '"+map.get("channelId")+"'";
			}
			if(map.containsKey("operatelId")){
				hql = hql+" and "+entity_alias_name+".readOperate.id = '"+map.get("operatelId")+"'";
			}
		}
		return hql;
	}
	@Override
	public List<Map<String, Object>> getBeanInfo() {
		List<Map<String, Object>> beaninfo = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(json_key, "title");
		map.put(json_title, "标题");
		map.put("width", 180);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "lastUpdateTime");
		map.put(json_title, "更新时间");
		map.put("width", 90);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "subcribeTime");
		map.put(json_title, "发布时间");
		map.put("width", 90);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "status");
		map.put(json_title, "状态");
		map.put("width", 50);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "channelTitle");
		map.put(json_title, "所属频道");
		map.put("width", 50);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "type");
		map.put(json_title, "类型");
		map.put("width", 50);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "author");
		map.put(json_title, "作者");
		map.put("width", 50);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "shareCommentsCount");
		map.put(json_title, "分享|评论");
		map.put("width", 70);
		beaninfo.add(map);
		return beaninfo;
	}
	@Override
	public IArticleDao getDao() throws Exception {
		// TODO Auto-generated method stub
		return articleDao;
	}

	@Override
	public List<JsonOperation> getOpts(String url,String id) {
		List<JsonOperation> opts = new ArrayList<JsonOperation> ();
		Date createDate = null;
		Article article = null;
		//用来格式化时间格式，方便在预览的时候请求静态资源
		DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
		String dateParam = "";
		try {
			//获取当前资讯信息
			article = super.getObject(id);
			if(null != article){
				createDate = article.getCreateTime();
				dateParam = df.format(createDate);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Integer status = null;
		try {
			article = super.getObject(id);
			status = article.getStatus();
		} catch (Exception e) {
			e.printStackTrace();
		}
		JsonOperation opt= new JsonOperation();
		opt.setName("修改");
		opt.setUrl(getCtx().getContextPath()+"/"+url+"/getinfo/"+id+"/edit"+url);
		opt.setType("edit");
		opts.add(opt);
		opt= new JsonOperation();
		opt.setName("删除");
		opt.setUrl(getCtx().getContextPath()+"/"+url+"/"+id+"?_requestMethod=delete");
		opt.setType("delete2");
		opts.add(opt);
		opt= new JsonOperation();
		opt.setName("预览");
		opt.setUrl(getCtx().getContextPath()+"/p/article/sec/"+ dateParam +"/" + id); 
		opt.setType("preview");
		opts.add(opt);
		return opts;
	}
	@Autowired
	@Qualifier("daoarticle")
	private IArticleDao articleDao;
	public IArticleDao getArticleDao() {
		return articleDao;
	}

	public void setArticleDao(IArticleDao articleDao) {
		this.articleDao = articleDao;
	}
	@Override
	public List<Map<String, Object>> grid(Map<String, String> querywhere) {
		try {
			Integer start = this.getGridStartOrSize(querywhere, 0, field_grid_start);
			Integer size = this.getGridStartOrSize(querywhere, 20, field_grid_size);
			String hql = this.getHql(querywhere);
			hql += " order by t.createTime desc ";
			Map<String,String> gridsel = new HashMap<String,String>();
			gridsel.put(field_id, ""+entity_alias_name+".id as id ");
			gridsel.put(field_title, ""+entity_alias_name+".title as title ");
			gridsel.put("status", "case when "+entity_alias_name+".status = 0 then '草稿' "
					+ " when "+entity_alias_name+".status = 1 then '待审核' "
					+ " when "+entity_alias_name+".status = 2 then '已发布'  end as status ");
			gridsel.put("lastUpdateTime", sql_date_method+"("+entity_alias_name+".lastUpdateTime ,'"+sql_time_format+"' ) as lastUpdateTime ");
			gridsel.put("subcribeTime", sql_date_method+"("+entity_alias_name+".subcribeTime  ,'"+sql_time_format+"' ) as subcribeTime ");
			gridsel.put("readOperateTitle", "ro.title as readOperateTitle ");
			gridsel.put("channelTitle", "ch.title as channelTitle ");
			gridsel.put("type", "case when "+entity_alias_name+".type = 1 then '资讯' else '视频' end as type ");
			gridsel.put("author", "au.userName as author ");
			gridsel.put("shareCommentsCount", ""+entity_alias_name+".shareCount || '|' || "+entity_alias_name+".commentsCount "
					+ "  as shareCommentsCount ");
			
			return this.queryMapDataList(hql, gridsel, start, size);
		} catch (Exception e) {
			return new ArrayList<Map<String, Object>>();
		}
		
	}
	/**
	 * 更新频道排序规则
	 * 获得所有视频排序类型大于等于新闻，但不等于100的数据
	 * @param article
	 */
	@SuppressWarnings({ "unused", "unchecked" })
	synchronized public void  updateChannelOrderType(Article article){
		String id = article.getId();
		String sql = "  select t from com.magicode.cms.entiy.base.Article t "
				+ " where t.channelOrderTypeInt != 100 and t.channelOrderTypeInt >= "+article.getChannelOrderTypeInt()+" "
						+ "and t.id != '"+id+"' ";
//		获得所有视频排序类型大于等于新闻，但不等于100的数据
		List<Object> articleList = this.queryDataList(sql);

		Integer tempOrderType = article.getChannelOrderTypeInt();
		for(Object obj : articleList){
			if(obj instanceof Article){
				Article tempNews = (Article) obj;
				Integer typeInt = tempNews.getChannelOrderTypeInt();
				tempOrderType++;
				if((tempOrderType) > 3 ){
					tempOrderType = 100;
				}
				tempNews.setChannelOrderTypeInt(tempOrderType);
//				this.
//				this.editObject(tempNews);
				try {
					this.getDao().getCommonDaoService().merge(tempNews);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unused" })
	@Override
	public void setupHead(News news) throws BusinessException {
		// TODO Auto-generated method stub
		if(true){
			return;
		}
		String id = news.getId() ;
				if(news.getHead() != null && news.getHead() == 1){ 
					String hql = "select t from " +Article.class.getName()+" t where t.head = 1";
					Map map = new HashMap();
					if(id  != null && id.trim().length() > 0){
						hql += "and t.id != '"+id+"'";
//						map.put("id", id);
						
					}
					List<Object> list = null;
//					if(map.isEmpty()){
						list = this.queryDataList(hql);
//					}
//					else{
//						list = this.queryDataList(hql,map);
//					}
					for(Object otherNews : list){
						if(otherNews instanceof News){
							((News)otherNews).setHead(0);
							try {
								this.getDao().editObject((News) otherNews);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
								throw new BusinessException(e);
							}
						}
					}
		}
	}
	
	//循环删除
	@Override
	public String deleteAll(Map<String, String> map) throws Exception {
		String hql ="from " +Article.class.getName()+" "+entity_alias_name+" ";
		while(null!=map && !map.isEmpty()){
			hql = "delete from"+entity_alias_name+".id = '"+map.get(field_id)+"'";
			System.out.println(hql);
		}
		return hql;
	}
	@Override
	public List<NewsEnterpriseRela> getNewsEnterpriseRela(String id) {
		List<NewsEnterpriseRela> videoList = new ArrayList();
		Article enterprise = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		String[] fetchJoins = new String[9];
		fetchJoins[0] = "mainPic";
		fetchJoins[1] = "source";
		fetchJoins[2] = "channel";
		fetchJoins[3] = "readOperate";
		fetchJoins[4] = "author";
		fetchJoins[5] = "enterpriseRelaList";
		fetchJoins[6] = "contributeStatus";
		fetchJoins[7] = "uniqueTime";
		fetchJoins[8] = "headPic";
		try {
			enterprise =super.getObject(id,fetchJoins);
		} catch (Exception e) {
			e.printStackTrace();
		}
		videoList = enterprise.getEnterpriseRelaList();
		return videoList;
	}
	@Override
	public List<NewsPersonRela> getNewsPersonRela(String id) {
		List<NewsPersonRela> videoList = new ArrayList();
		Article enterprise = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		String[] fetchJoins = new String[9];
		fetchJoins[0] = "mainPic";
		fetchJoins[1] = "source";
		fetchJoins[2] = "channel";
		fetchJoins[3] = "readOperate";
		fetchJoins[4] = "author";
		fetchJoins[5] = "personRelaList";
		fetchJoins[6] = "contributeStatus";
		fetchJoins[7] = "uniqueTime";
		fetchJoins[8] = "headPic";
		try {
			enterprise =super.getObject(id,fetchJoins);
		} catch (Exception e) {
			e.printStackTrace();
		}
		videoList = enterprise.getPersonRelaList();
		return videoList;
	}
	@Override
	public List<NewsProgramRela> getNewsProgramRela(String id) {
		List<NewsProgramRela> videoList = new ArrayList();
		Article enterprise = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		String[] fetchJoins = new String[9];
		fetchJoins[0] = "mainPic";
		fetchJoins[1] = "source";
		fetchJoins[2] = "channel";
		fetchJoins[3] = "readOperate";
		fetchJoins[4] = "author";
		fetchJoins[5] = "programList";
		fetchJoins[6] = "contributeStatus";
		fetchJoins[7] = "uniqueTime";
		fetchJoins[8] = "headPic";
		try {
			enterprise =super.getObject(id,fetchJoins);
		} catch (Exception e) {
			e.printStackTrace();
		}
		videoList = enterprise.getProgramList();
		return videoList;
	}
	
	/*
	 *上传多个配图
	 */
	@Override
	public List<Picture> getPictures(String id) {
		List<Picture> picList = new ArrayList();
		String sql = " select p from "+Picture.class.getName()+" p , "+News.class.getName()+" t "
				+ " where p in elements(t.relaPics) and t.id = :id order by p.id ";
		Article tvFilmPerson = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		try {
			picList = this.articleDao.getCommonDaoService().queryList(sql, map);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return picList;
	}
	
	@Override
	public void deletPiclist(String userid){
		
		this.articleDao.deletPiclist(userid);
	}
	
	@Override
	public long findCountArticle(Date subDate) {
		return this.articleDao.findCountArticle(subDate);
	}
}
